<?php
/**
* Ebay Client class provides an abstracted means of making requests to Ebay through their own API
* There api can be found here - @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/index.html
* @author Luke Parry <lparry@shodan.nl>
* @category Ebay
* @package Client
*/
class Ebay_Client
{
	private $_request; //Ebay Http Client
	private $_xml;
	private $_config;
    static private $_uid = false;
	private $_ready = false;

	
	/**
	 * @static Static function that sets the Uid, to get the auth token from the databae.
	 * @todo Later should be modularised into a seperate inherited class
	 * @param integer $uid the Uid to load from the database.
	 */
    static public function setUid($uid)
    {
        self::$_uid = $uid;
    }

	
	/**
	 * The Class constructor
	 * @param string $server the server that the application should connnect to, default Sandbox
	 *
	 */
	public function __construct($server = 'Sandbox')
	{
	    $this->_request = new Ebay_HttpClient();
        //$this->_request->init(); //Initialise the newly created object
		
        $this->_xml = new Ebay_XmlWriter();
		$this->_xml->create();

        //Load the session to check if the token has already been checked and cached
        $user = new Zend_Session_Namespace('User');

        if(!self::$_uid)
        {
            throw new Ebay_Exception('The Uid has not been provided through the static call');
        }
		
        //Create an ebayAuthKey to check otherwise a previously stored token to check it's status
        $ebayAuthKey = new Ebay_AuthKey(self::$_uid);

		$this->_config = Zend_Registry::getInstance()->get('config')->ebay->api;
        if(isset($user->tokenValid))
        {
            Ebay_HttpClient::setAuthToken($ebayAuthKey->getToken());

            $this->_ready = true;
        }
        elseif ($ebayAuthKey->getTokenStatus())
		{
			Ebay_HttpClient::setAuthToken($ebayAuthKey->getToken());

            $user->tokenValid = true; //Store this in the session
            $this->_ready = true;
		}
		else
		{
			//Inform the user, it should trigger a change.

		}
	}

	/**
	 * Convenience method to call an Ebay API Call, that includes the xml property
	 * of the class
	 * @param string $callName the request API name to be made
	 * @return SimpleXMLElement
	 */
    private function _call($callName)
    {
        return $this->_request->call($callName, $this->_xml);
    }
	
	/**
	 * Cleans and prepares the private xml member
	 */
	private function _prepareXML()
	{
		$this->_xml->delete()->create();
	}
	
	/**
	 * Submits an Item to Ebay without verification
	  * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/AddItem.html
	 * @param stdClass $item the Listing to be submitted
	 * @return stdClass the new status for the submitted listing
	 */
	public function addItem($item)
	{
		$this->_prepareXML();
        $this->formatItem($item);
        $response = $this->_call('AddItem');

        //process the fees item Id
		$status = new stdClass();
        $status->ebayId = $response->ItemID;
		
		// Keep the time in GMT
        $status->submitted = $response->StartTime;
        $status->finishes = $response->EndTime;
		
		return $status;
	}
	
	/**
	 * Complete the sale of a transaction for a given Listing
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/CompleteSale.html
	 * @param integer $transactionId the  transaction id for a particular item
	 * @param integer $ebayId the EbayId for a listing
	 * @param array $params any optional parameters
	 * @return boolean
	 */
	public function completeSale($transactionId, $ebayId, $params = array())
	{
		$this->_prepareXML();
		
		$this->_xml->push('ItemID', $ebayId)->pop()
				   ->push('TransactionID', $transactionId)->pop();
				   
		if(sizeof($params) > 0)
		{
			$this->_xml->pushElements($params);
		}
		$this->_call('CompleteSale');
		// There is no output worth returning therefore if no exceptions are thrown, return true
		return true;
	}
	
	/**
	 * Ends an item early if applicable by Ebay 
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/EndItem.html
	 * @param integer $ebayId the listing's ebayId to end
	 * @param string $reason a suitable code to describe why the listing finished early
	 * @return boolean
	 */
	public function endItem($ebayId, $reason)
	{
		// Check if the reason given is an acceptable code
		if(!in_array($reason, Ebay_Codes::get('EndReason')))
		{
			return false;
		}
		
		$this->_prepareXML();
        $this->_xml->push('ItemID', $ebayId)->pop()
				   ->push('EndingReason', $reason)->pop();
		
		$response = $this->_call('EndItem');
		return (isset($response->EndTime)) ? true : false;
	}
	
	
	/**
	 * Formats a given item into an acceptable XML format for the request sent to Ebay
	 * @param array $item - the listing to be formatted
	 * @param array | stdClass $params - extra parameters that can extend the item's details
	 */
    public function formatItem($item, $params = null)
    {
        // Get the Ebay User details, needed for post code currently
		$ebayUser = $this->getUser();
			
		//Important re-create the xml document as a transaction has already been sent.
		$this->_prepareXML();
		
        // Start the Item Element
        $this->_xml->push('Item')
                   ->push('Country', $this->_config->country)->pop()
                   ->push('Currency', $this->_config->currency)->pop();

        //Add any attributes associated with the item
        $this->_xml->push('AttributeArray')->pop();
       /*
	         * Write the Description but using CData tag to ensure that everything
	         * is escaped and the description doesn't conflict with the XML.
	         */
        $this->_xml->push('Description');
        $this->_xml->writeCData($item['description']);
        $this->_xml->endCData();

		// Grab a copy of the user's account
        $user = Zend_Registry::getInstance()->user;
        $user->data = (is_string($user->data)) ? unserialize($user->data) : $user->data;
		
		// Unserialise any extra details stored about the item
		$item['details'] = unserialize($item['details']);
		
		/*
		* Note: Listing Duration needs the days to be presented in format 'Days_xx'
		*
		*/
        $this->_xml->pop()->push('StartPrice', $item['startPrice'])->pop()
                   ->push('ListingDuration', 'Days_' . $item['duration'])->pop()
                   ->push('PrimaryCategory')
                   ->push('CategoryID', $item['cid'])->pop(2)
                   ->push('Quantity', 1)->pop()
                   ->push('Title', $item['title'])->pop()
                   ->push('PostalCode', $ebayUser->RegistrationAddress->PostalCode)->pop();
	   
	   /*
		* Iterate through all the payment options enabled for the item
		* If Paypal email address has been provided and has been allowed for the item
		*/
		
		if(isset($item['details']->paymentOptions))
		{
			// Explode the string of payment options back into an array : 'PayPal, Ebay' to array('PayPal, 'Ebay')
			$options = explode(',' ,$item['details']->paymentOptions);
			
			foreach($options as $option)
			{
				// Presumption that the payment methods are validated prior
				$this->_xml->push('PaymentMethods', $option)->pop();
			}
			if(in_array('PayPal', $options))
			{
				$address = (isset($item['details']->paypalAddress)) ? $item['details']->paypalAddress : $user->paypal;
				$this->_xml->push('PayPalEmailAddress', $address )->pop();
			}
		}
        if(isset($item['images']))
        {
            $this->_xml->push('PictureDetails');

            foreach($item['images'] as $image)
            {
				//Get the site url
                $this->_xml->push('PictureURL', 'http://pazmonster.com/images/'. $image['filename'])->pop();
		
                //Add the gallery if it is enabled and the url of the image;
                if(!is_null($item['gallery']) && $item['gallery'] == $image['pid'])
                {
                    $this->_xml->push('GalleryURL', $galleryUrl)-pop()
                               ->push('GalleryType', 'Gallery')->pop();
                }
            }

            $this->_xml->pop();
        }
		
		// Add any extra paramers by iterating over them
		if(isset($params))
		{
			$this->_xml->pushElements($params);
		}
        $this->_xml->pop(); // Close the Item Element
    }
	
	
	/**
	 * Get the current bidder history in greater detail for an EbayId
	 * @param integer $ebayId the ebayId of the listing 
	 * @param boolean $simple whether the request should produce a simplified output
	 * @return SimpleXMLElement
	 */
	public function getAllBidders($ebayId, $simple = null)
	{
		$this->_prepareXML();
		$this->_xml->push('ItemID', $ebayId)->pop()
				   ->push('CallMode', 'ViewAll')->pop();
		
		if(isset($simple))
		{
			$this->_xml->push('OutputSelector','BidArray.Offer.UserID')->pop();
		}
		
		return $this->_call('GetAllBidders');	
	}
	
	/**
	 * Get a list of current categories
	  * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetCategories.html
	 * @param integer $cid the category id to get the parent  categories from
	 * @return SimpleXMLElement
	 */
	public function getCategories($cid = 0)
	{
        $this->_prepareXML();

        //Only return the top categories if no cid is provided
        if($cid != 0)
        {
            $this->_xml->push('CategoryParent', $cid)->pop();
        }

        return $this->_call('GetCategories');
	}

    public function getCategorySpecifics($cid, $maxNames = null, $maxValues = null)
    {
        $this->_prepareXML();
        $this->_xml->push('CategoryID', $cid)->pop();
        $this->_xml->push('DetailLevel', 'ReturnAll')->pop();
        if(isset($maxNames)) $this->_xml->push('MaxNames', $maxNames)->pop();
        if(isset($maxValues)) $this->_xml->push('MaxValuesPerName', $maxValues)->pop();

        return $this->_call('GetCategorySpecifics');
    }

    public function getCatgoryFeatures($cid, $features = null, $outputs = array())
    {
        $this->_prepareXML();
		
		if(sizeof($outputs) > 0)
		{
			$this->_xml->push('OutputSelector', implode(',', $outputs))->pop();
		}
		
        $this->_xml->push('CategoryID', $cid)->pop();
        $this->_xml->push('DetailLevel','ReturnAll')->pop();

        if(isset($features) && is_array($features))
        {
            foreach($features as $feature)
            {
                $this->_xml->push('FeatureID', $feature)->pop();
            }
        }
        return $this->_call('GetCategoryFeatures');
    }

	
    /**
	 * Get updates to the category hierarchy
	 *
	 */
    public function getCategoryMappings($version)
    {
        $this->_prepareXML();
        $this->_xml->push('CategoryVersion', $version)->pop();
        $this->_xml->push('DetailLevel','ReturnAll')->pop();
        return $this->_call('GetCategoryMappings');
    }

	
	/**
	 * Get the current version of Ebay category hierarchy
	 *
	 */	
    public function getCategoryVersion()
    {
        $this->_prepareXML();

        $data =  $this->_call('GetCategories');
        return $data->CategoryVersion;
    }
	
	/**
	 * Get the current Item details
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetItem.html
	 * @param integer $ebayId the listings ebayId to fetch the item
	 * @param array $outputs any parameters to be sent in the request to manipulate the output
	 * @return SimpleXMLElement
	 */
	public function getItem($ebayId, $outputs = array())
	{
		$this->_prepareXML();
		
		if(sizeof($outputs) > 0)
		{
			$this->_xml->push('OutputSelector', implode(',',$outputs))->pop();
		}
		
		$this->_xml->push('ItemID', $ebayId)->pop();
		
		return $this->_call('GetItem');
	}
	
	public function getItemTransactions($ebayId, $params = array(), $outputs = array())
	{
		$this->_prepareXML();
		if(sizeof($params) > 0)
		{
			$this->_xml->pushElements($params);
		}
		
		if(sizeof($outputs) > 0)
		{
			$this->_xml->push('OutputSelector', implode(',', $outputs))->pop();
		}
		
		$this->_xml->push('ItemID', $ebayId)->pop();
	
		return $this->_call('GetItemTransactions');
	}
	
	/**
	 * Get the latest events for the sellers items, such as new bids, watches
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetSellerEvents.html
	 * @param Zend_Date $from the date to get the earliest events from: mandatory
	 * @param Zend_Date $to the date to get the latest events to
	 * @param array $outputs any parameters to be sent in the request to manipulate the output
	 * @return Simple_XMLElement
	 */
	public function getSellerEvents($from, $to = null, $outputs = array())
	{
		$this->_prepareXML();
		if(sizeof($outputs) > 0)
		{
			$this->_xml->push('OutputSelector', implode(',', $outputs))->pop();
		}
		
		$this->_xml->push('DetailLevel', 'ReturnAll')->pop()
				   ->push('IncludeWatchCount', true)->pop()
				   ->push('ModTimeFrom', $from->get(Zend_Date::ISO_8601))->pop();
				   
		if(isset($to))
		{
			$this->_xml->push('ModTimeTo', $to->get(Zend_Date::ISO_8601))->pop();
		}
		
		return $this->_call('GetSellerEvents');
	}
	
	/**
	 * Get all the transaction for the seller
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetSellerTransactions.html
	 * @param Zend_Date $from the date to get the earliest events from: mandatory
	 * @param Zend_Date $to the date to get the latest events to
	 * @param array $outputs any parameters to be sent in the request to manipulate the output
	 * @return SimpleXMLElement
	 */
	public function getSellerTransactions($from, $to = null, $outputs = array())
	{
		$this->_prepareXML();
		if(sizeof($outputs) > 0)
		{
			$this->_xml->push('OutputSelector', implode(',', $outputs))->pop();
		}
		
		$this->_xml->push('DetailLevel', 'ReturnAll')->pop()
				   ->push('IncludeFinalValueFee', true)->pop();
				   
		if(isset($to))
		{
			$this->_xml->push('ModTimeTo', $to->get(Zend_Date::ISO_8601))->pop();
		}
		return $this->_call('GetSellerTransactions');
	}
	
	/**
	 * Get the currently signed in user's details, who's token is being used for the request.
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetUser.html
	 * @return SimpleXMLElement
	 */
	public function getUser()
	{
		$this->_prepareXML();
		$this->_xml->push('DetailLevel', 'ReturnAll')->pop();
		
        $data =  $this->_call('GetUser');		
		return $data->User;
	}
	
	
	/**
	 * Get the currently signed in user's preferences, who's token is being used for the request
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/GetUserPreferences.html
	 * @return SimpleXMLElement
	 */
	public function getUserPreferences()
	{
		$this->_prepareXML();
		$this->_xml->push('DetailLevel', 'ReturnAll')->pop();
		
        $data =  $this->_call('GetUserPreferences');		
		return $data;
	}
	
	
	/**
	 * Syncs the current User's listings with the current status in Ebay. If it is a major sync, syncTranscations should
	 * be enabled so that it can get a list of item transactions in batch.
	 * @param integer $uid - sync a different user provided by the Uid 
	 * @param boolean $syncTransactions if true uses getSellerTransactions else calls getItemTransactions for each item if it has finished
	 * @return array | boolean
	 */
    public function sync($uid = null, $syncTransactions = null)
    {
		// Get the current user from the model, if the user isn't found within the registry
		if(isset($uid))
		{
			$User = new User();
			$user = $User->getUserById($uid);
		}
		else
		{
			$registry = Zend_Registry::getInstance();
			$user = $registry->user;
		}
		
		// Get the  date and time of the last synced update from the user record
		$from = new Zend_Date($user->sync, 'ISO_8601');

		// Get the current date and time
		$currentDate =  new Zend_Date();
		//Make a copy of the date to compare with
		$checkDate = $from;
		$checkDate->add($this->_config->syncInterval, Zend_Date::MINUTE);
		
		if(is_null($user->sync) || $currentDate->isLater($checkDate) )
		{ // Current sync time is later than the permitted sync Interval
			$response = $this->getSellerEvents($from);
			//Update the synced date for the user
			$user->sync = $response->TimeTo;
			
			//Save the user with the new sync times
			$user->save();
			
			// Keep the registry copy upto date in case, if the user was fetched from the registry
			if(isset($uid))
			{			
				$registry->user = $user;
			}
			
			$Items = new Items(); // Load up the item modal ready to append changes
			$Status = new Status();

			//Check if there are items to be updated
			if(isset($response->ItemArray) && sizeof($response->ItemArray) > 0)
			{
				$listings = array();
				foreach($response->ItemArray->Item as $item)
				{					
					$statusRow = $Status->getByEbayId($item->ItemID);
					
					if(!$statusRow)
					{
						// The item that has been sold hasn't been created through this tool - ignore
						continue;
					}
					/*
					 * Check if the Item has finished, by checking if the item's listing status has changed
					 * however the item hasn't been updated already
					 */
					if($item->SellingStatus->ListingStatus == 'Completed')
					{
						// The item has 'ended' or 'completed'
						
						if(is_null($syncTransactions))
						{
							// Get the Item from Ebay to ensure the item has sold
							$this->processTransactions( $this->GetItemTransactions($item->ItemID) );
						}
								
						if($item->ListingType == 'Chinese' || $item->ListingType == 'Dutch')
						{
							// Chinese and Dutch Auctions only have a bid count and indicate whether an item has a winning big
							
							if($item->SellingStatus->BidCount > 0)
							{
								$statusRow->status = 3;								
							}
							else
							{
								$statusRow->status = 2;
							}
							
						}	
						else
						{
							//Multi-item and special listings go here
						}
					}
			
					if($item->ListingType == 'Chinese' || $item->ListingType == 'Dutch')
					{
						$statusRow->bids = $item->SellingStatus->BidCount;
						$statusRow->currentPrice = $item->SellingStatus->CurrentPrice;
					}
					
					/*
					if($statusRow->currentPrice != $item->SellingStatus->CurrentPrice)
					{						
							$bidders = $this->getAllBidders($item->ItemID, true);
							
							// Check there are actually bids that have been made
							if(isset($bidders->BidArray) && isset($bidders->BidArray->Offer))
							{
								$statusRow->bids = sizeof($bidders->BidArray->Offer);
							}						
					}*/				
					
					$statusRow->watches = (isset($item->WatchCount)) ? $item->WatchCount: 0;					
					$statusRow->save(); // Save the status
					$listings[] = $statusRow->id;
				}
				
			}

			// if syncTransactions paramter is enabled, Check now for any items that have finished , and get all the item transcations
			if(isset($syncTransactions))
			{
				$this->_xml->delete();
				$transactionResponse = $this->getSellerTransactions($from);
				$this->processTransactions($transactionResponse);
			}
			
			return $listings;
			//End of sync block
		}
		else
		{	// The user is trying to sync to earlier.
			return false;
		}
	}
	
	/**
	 * Processes transactions provided by either getItemTransactions or getSellerTransactions
	 * @param SimpleXMLElement $transaction the transaction element from the Transaction Array
	 */
	private function processTransactions($transactions)
	{
		if(!isset($transactions->TransactionArray->Transaction) && sizeof($transactions->TransactionArray->Transaction) == 0 )
		{			
			return false; // No transactions		
		}
		
		// Load the database models
		$TransactionDB = new Transactions();
		$Status = new Status();
		$Buyers = new Buyers();
		
		foreach($transactions->TransactionArray->Transaction as $transaction)
		{
			$ebayId = $transaction->Item->ItemID;				
			$itemStatus = $Status->getByEbayId($ebayId);
			if(!$itemStatus)
			{
				// The transaction doesn't belong to any listings submitted by the app
				continue;
			}
			
			// Calculate the status of the current transaction
			if($transaction->status->CompleteStatus == 'Complete')
			{
				$transactionStatus = 3;
			}
			elseif($transaction->Status->PaymentMethodUsed == 'Paypal')
			{
				if($transaction->Status->eBayPaymentStatus != 'PayPalPaymentInProcess')
				{
					// An error has occured with payment
					$transactionStatus = 2;
				}
				else
				{
					$transactionStatus = 0;
				}
			}
			else
			{
				// Another payment method has been chosen
				$transactionStatus = 0;
			}
			
			// Try and locate the transaction for  the Item, if it has already been created				
			$transactionRow = $TransactionDB->getByEbayId($ebayId);
			
			// Create a transaction if it doesn't already exist
			if(!$transactionRow)
			{
				$transactionRow = $TransactionDB->createRow();				
			}
			
			// Depending on whether the item is a chinese auction, locate a previous buyer record
			if($transaction->Item->ListingType == 'Chinese')
			{
				// Check to see if a previous customer is already stored in the database
				$buyerRow = $Buyers->getByEbayUid($transaction->Buyer->UserID);
			}
			else
			{
				// Check to see if a previous customer is already stored in the database
				$buyerRow = $Buyers->getByTid($transaction->TransactionID);
			}
			
			// Just check if a record was found, fall back to creating a new row for the new customer
			if(!$buyerRow)
			{
				$buyerRow = $Buyers->createRow();
			}
			
			// Store or update the address details everytime - may not be necessary
			if($transaction->Buyer->BuyerInfo->ShippingAddress)
			{
				// Create some references
				$buyer = &$transaction->Buyer;
				$shipping = &$buyer->BuyerInfo->ShippingAddress;
				
				$buyerData = array('ebayUid'   => $buyer->UserID,
								   'name'	   => $shipping->Name,
								   'country'   => $shipping->CountryName,
								   'street'    => $shipping->Street,
								   'city'	   => $shipping->CityName,
								   'province'  => $shipping->StateOrProvince,
								   'postcode'  => $shipping->PostalCode,
								   'phone'	   => ($shipping->Phone == 'Invalid Request') ? null : $shipping->Phone,
								   'email'	   => $buyer->Email,
								   'score'	   => $buyer->FeedbackScore,
								   'percent'   => $buyer->PositiveFeedbackPercent);
			}
			// The lastime the transaction was modified by Ebay, useful to identify transactions that haven't  been paid for.
			$transactionLastModified = new Zend_Date($transaction->Status->LastTimeModified, 'ISO_8601');
			
			// Prepare an array to update a record
			$data = array('ebayId' 		=> $ebayId,
						  'type'   		=> $transaction->Status->PaymentMethodUsed, // The selected payment type
						  'status' 		=> $transactionStatus,
						  'lastModified'=> $transactionLastModified,
						  'sale'   		=> $transaction->TransactionPrice,
						  'fee'	   		=> $transaction->FinalValueFee,
						  'ebayUid' 	=> $buyer->UserID);
			
			$buyerRow->setFromArray($buyerData)->save();
			
			// @TODO CHANGE TO A SWITCH BLOCK SOMETIME IN DA FUTURE
			//Process the chinese listing to update status
			if($transaction->Item->ListingType == 'Chinese')
			{
				$data['tid'] = 0; // A chinese auction doesn't have a Transaction Id (Tid)
				
				$itemStatus = $Status->getByEbayId($ebayId);
				
				// We can safely modify the Status of the Item
				$itemStatus->bids = $transaction->Item->SellingStatus->BidCount;
				$itemStatus->currentPrice = $transaction->Item->SellingStatus->CurrentPrice;
				
				// Check to see whether a payment has been made, since there is only one transaction for a chinese auction
				if($transactionStatus == 2)
				{
					$itemStatus->status = 4;
				}
				
				$itemStatus->save();
				
				// Update the transaction record, whether new or old
				$transactionRow->setFromArray($data);							
				$transactionRow->save();
			}
			else
			{
				// Screw multi-item listings at the momment, not in spec
			}
		}
	}
	public function syncUser()
	{
	
	}
	
    public function relistItem($item)
    {
		
		$params = array('ItemID' => $item['ebayId']);
		
		$this->formatItem($item, $params);
		
        $response = $this->_call('RelistItem');
		return $response;
    }
	
	/**
	 * If an alternative payment to paypal is made, such as cheque, postal order, the User must and can update the status
	 * of the listing to indicate the exchange of payment has been made. If the item was not a chinese auction
	 * a TransactionID must be passed as a parameter
	 * @link http://developer.eay.com/devzone/xml/docs/reference/ebay/ReviseCheckoutStatus.
	 * @param intenger $ebayId the EbayId of the listing
	 * @param string $checkoutStatus a token to change the current status of payment
	 * @param array $params an optional array of arguments for the api call
	 * @throws Ebay_Exception if an invalid CompleteStatus token was provided
	 */
	public function reviseCheckoutStatus($ebayId, $checkoutStatus, $params = array())
	{
		//Check to see whether the checkoutStatus token is valid
		if( !in_array($checkoutStatus, Ebay_Codes::get('CompleteStatus')) )
		{
			throw new Ebay_Exception('The CompleteStatus token provided was invalid');		
		}
		
		$this->_xml->create();
		
		if(sizeof($params) > 0)
		{
			$this->_xml->pushElements($params);
		}
		
		$this->_xml->push('ItemID', $ebayId)->pop()
				   ->push('CheckoutStatus', $checkoutStatus)->pop();
				   
		$this->_call('ReviseCheckoutStatus');
	}
	
	/**
	 * Revise an listing given by an EbayId by appending, modifiying or deleting fields
	 * @param integer $ebayId the listing to revise, provided by the EbayId
	 */
	public function reviseItem($ebayId)
	{
		
	}

    private function updateItemStatus()
    {

    }


	/**
	 * Calls VerifyItem hat behaves like AddItem but doesn't make the listing active, instead returns fees
	 * @link http://developer.ebay.com/devzone/xml/docs/reference/ebay/VerifyAddItem.html
	 * @param array $item the  item that is to be submitted
	 * @return SimpleXMLElement
	 */
    public function verifyAddItem($item)
    {
        $this->formatItem($item);

        //Submit listing data to the server
        $response = $this->_call('VerifyAddItem');
        //Calculate fees according share with relist and additem
        return $response;
    }
}